package huaweiod.first;

/**
 * 华为OD机试真题 Java 实现【单词倒序】【2022.11 Q4 新题】
 */
public class A_2023_37_LetterReverse {

    public static String letterReverse(String str) {
        if(str == null || str.length() == 0) {
            return "";
        }
        String ans = "";
        String temp = "";
        char[] chars = str.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            char c = chars[i];
            if(Character.isLetter(c)) {
                temp += c;
            } else if(c == ' ') {
                ans += reverse(temp) + " ";
                temp = "";
            } else {
                ans += reverse(temp) + c;
                temp = "";
            }
            if(i == chars.length - 1 && temp.length() > 0) {
                ans += reverse(temp);
            }
        }
        return ans;
    }

    public static String reverse(String letter) {
        StringBuilder ans = new StringBuilder();
        for (int i = letter.length() - 1; i >= 0; i--) {
            ans.append(letter.charAt(i));
        }
        return ans.toString();
    }

    public static void main(String[] args) {
        System.out.println(letterReverse("woh era uoy ? I ma enif."));
    }
}
